<template>
  <div class="user-blacklist-page">
    <el-card>
      <table-bar :show-top="true" :show-bottom="true" @search="search" @reset="clear">
        <template #top>
          <el-form :inline="true" :model="formInline" class="form-search">
            <el-form-item label="用户信息">
              <el-input
                v-model="formInline.search"
                maxlength="30"
                placeholder="请输入用户ID/名称/手机号"
                clearable
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="formInline.state"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="生效" :value="1" />
                <el-option label="失效" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查看</el-button>
              <el-button @click="clear">重置</el-button>
              <el-button type="success" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </template>
      </table-bar>

      <art-table
        :data="tableData"
        :loading="tableLoading"
        :border="true"
        :total="total"
        :current-page="formInline.page"
        :page-size="formInline.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :show-header-background="true"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="buyerUserId" label="用户ID" min-width="120" />
        <el-table-column prop="name" label="用户昵称" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="openId" label="微信openId" min-width="150" />
        <el-table-column prop="state" label="状态" min-width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.state ? 'success' : 'danger'">
              {{ scope.row.state ? '生效' : '失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column prop="updateTime" label="更新时间" min-width="180" />
        <el-table-column label="操作" fixed="right" width="160" align="center">
          <template #default="scope">
            <button-table
              :type="scope.row.state ? 'edit' : 'edit'"
              :text="scope.row.state ? '失效' : '生效'"
              @click="handleToggleState(scope.row)"
            />
            <button-table type="delete" text="删除" @click="handleDelete(scope.row)" />
          </template>
        </el-table-column>
      </art-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible.form"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="选择用户" prop="buyerUserId">
          <el-select
            v-model="searchKey"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="userQuery"
            :loading="userLoading"
            value-key="buyerUserId"
            @change="userSelectChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.buyerUserId"
              :label="`${item.name} (${item.phone || '无手机号'})`"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="user-result" v-if="selectedUser.buyerUserId">
        <el-descriptions class="margin-top" title="用户信息" :column="1" border>
          <el-descriptions-item>
            <template #label>用户ID</template>
            {{ selectedUser.buyerUserId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>昵称</template>
            {{ selectedUser.name || '无' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>手机号</template>
            {{ selectedUser.phone || '无' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>OpenID</template>
            {{ selectedUser.wechatOpenId || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.form = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, nextTick } from 'vue'
  import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
  import {
    getAllUserBlackList,
    saveRiskBlack,
    updateRiskBlack,
    deleteRiskBlack,
    searchUser
  } from '@/api/riskApi'
  import type {
    RiskBlackPageParam,
    RiskUserBlack,
    RiskBlackSaveParam,
    RiskBlackUpdateParam,
    RiskBlackDeleteParam,
    CereBuyerUser,
    UserSearchParam
  } from '@/api/model/riskModel'
  import { ApiStatus } from '@/utils/http/status'

  let formInline = ref<RiskBlackPageParam>({
    page: 1,
    pageSize: 10,
    search: ''
  })
  let tableLoading = ref(false)
  let dialogVisible = ref({
    form: false
  })
  let total = ref(0)
  let tableData = ref<RiskUserBlack[]>([])
  let formData = ref<RiskBlackSaveParam | RiskBlackUpdateParam>({
    type: 2,
    buyerUserId: undefined
  })
  let isEdit = ref(false)
  let formRef = ref<FormInstance>()

  // 用户查看相关变量
  let searchKey = ref('')
  let userLoading = ref(false)
  let userOptions = ref<CereBuyerUser[]>([])
  let selectedUser = ref<CereBuyerUser>({} as CereBuyerUser)

  const formRules = reactive<FormRules>({
    buyerUserId: [{ required: true, message: '请选择用户', trigger: 'blur' }]
  })

  const dialogTitle = ref('新增用户黑名单')

  onMounted(() => {
    getAll(formInline.value)
  })

  // 获取用户黑名单列表
  async function getAll(params: RiskBlackPageParam) {
    try {
      tableLoading.value = true
      const res = await getAllUserBlackList(params)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data?.list || []
        total.value = res.data?.total || 0
      }
    } catch (error) {
      console.error('获取用户黑名单列表失败:', error)
      ElMessage.error('获取用户黑名单列表失败')
    } finally {
      tableLoading.value = false
    }
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    formInline.value.pageSize = val
    getAll(formInline.value)
  }

  // 当前页码变化
  function handleCurrentChange(val: number) {
    formInline.value.page = val
    getAll(formInline.value)
  }

  // 查看
  function search() {
    formInline.value.page = 1
    getAll(formInline.value)
  }

  // 重置
  function clear() {
    formInline.value = {
      page: 1,
      pageSize: 10,
      search: '',
      state: undefined
    }
    getAll(formInline.value)
  }

  // 用户查看
  async function userQuery(query: string) {
    if (query) {
      userLoading.value = true
      try {
        const params: UserSearchParam = {
          page: 1,
          pageSize: 10,
          searchKey: query
        }
        const res = await searchUser(params)
        if (res.code === ApiStatus.success) {
          userOptions.value = res.data?.list || []
        }
      } catch (error) {
        console.error('用户查看失败:', error)
        ElMessage.error('用户查看失败')
      } finally {
        userLoading.value = false
      }
    } else {
      userOptions.value = []
    }
  }

  // 用户选择变化
  function userSelectChange(user: CereBuyerUser) {
    selectedUser.value = user
    formData.value.buyerUserId = user.buyerUserId
  }

  // 新增
  function handleAdd() {
    isEdit.value = false
    dialogTitle.value = '新增用户黑名单'
    formData.value = {
      type: 2,
      buyerUserId: undefined
    }
    searchKey.value = ''
    selectedUser.value = {} as CereBuyerUser
    userOptions.value = []
    dialogVisible.value.form = true
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // 删除
  async function handleDelete(row: RiskUserBlack) {
    try {
      await ElMessageBox.confirm('确定要删除此用户黑名单吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      tableLoading.value = true
      const deleteParam: RiskBlackDeleteParam = {
        id: row.id!
      }
      const res = await deleteRiskBlack(deleteParam)

      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        getAll(formInline.value)
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除用户黑名单失败:', error)
        ElMessage.error('删除用户黑名单失败')
      }
    } finally {
      tableLoading.value = false
    }
  }

  // 切换状态
  async function handleToggleState(row: RiskUserBlack) {
    try {
      const newState = !row.state
      const actionText = newState ? '生效' : '失效'

      await ElMessageBox.confirm(`确定要${actionText}此用户黑名单吗？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      tableLoading.value = true
      const updateParam: RiskBlackUpdateParam = {
        id: row.id!,
        type: row.type ?? 2,
        buyerUserId: row.buyerUserId,
        state: newState
      }
      const res = await updateRiskBlack(updateParam)

      if (res.code === ApiStatus.success) {
        ElMessage.success(`${actionText}成功`)
        getAll(formInline.value)
      } else {
        ElMessage.error(res.message || `${actionText}失败`)
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('切换状态失败:', error)
        ElMessage.error('切换状态失败')
      }
    } finally {
      tableLoading.value = false
    }
  }

  // 提交表单
  async function submitForm() {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      tableLoading.value = true

      if (isEdit.value) {
        const res = await updateRiskBlack(formData.value as RiskBlackUpdateParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('更新成功')
          dialogVisible.value.form = false
          getAll(formInline.value)
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      } else {
        const res = await saveRiskBlack(formData.value as RiskBlackSaveParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('新增成功')
          dialogVisible.value.form = false
          getAll(formInline.value)
        } else {
          ElMessage.error(res.message || '新增失败')
        }
      }
    } catch (error) {
      console.error('操作失败:', error)
    } finally {
      tableLoading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .user-search {
    margin-bottom: 20px;
  }

  .user-result {
    margin-top: 20px;

    :deep(.el-descriptions__title) {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 10px;
    }

    :deep(.el-descriptions__label) {
      font-weight: 500;
      color: #606266;
    }

    :deep(.el-descriptions__content) {
      color: #303133;
    }
  }

  .user-blacklist-page {
    padding: 20px;

    .form-search {
      margin-bottom: 15px;
    }

    // 响应式设计
    @media screen and (max-width: $device-phone) {
      padding: 10px;

      .form-search {
        .el-form-item {
          width: 100%;
          margin-bottom: 10px;

          .el-input {
            width: 100%;
          }
        }
      }

      .el-dialog {
        width: 90% !important;
      }
    }
  }
</style>
